package weixin

import (
	"bytes"
	"encoding/json"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/message_queue"
	"io"
	"net/http"
)

// 发送订阅消息
func MessageSend(message_queue message_queue.MessageQueue, jsonValue []byte) error {

	var access_token, err = AccessTokenGet()
	if err != nil {
		return err
	}

	// 将JSON数据写入请求的body中
	requestBody := bytes.NewBuffer(jsonValue)

	// 创建请求
	request, err := http.NewRequest("POST", "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+access_token, requestBody)
	if err != nil {
		return err
	}

	// 设置Header
	request.Header.Set("Content-Type", "application/json")

	// 执行请求
	client := &http.Client{}
	response, err := client.Do(request)
	if err != nil {
		return err
	}

	defer response.Body.Close()

	// 读取响应
	body, err := io.ReadAll(response.Body)
	if err != nil {
		return err
	}

	var resp struct {
		Errcode int    `json:"errcode"`
		Errmsg  string `json:"errmsg"`
	}

	err = json.Unmarshal(body, &resp)
	if err != nil {
		return err
	}

	// 记录响应结果
	message_queue.Result = "成功"

	if resp.Errcode != 0 {
		// 记录返回的错误信息
		message_queue.Result = "失败"
		message_queue.ErrorCode = int(resp.Errcode)
		message_queue.ErrorMessage = resp.Errmsg
	}

	if err := bean.MysqlDb.Where("`id`=?", message_queue.ID).Updates(&message_queue).Error; err != nil {
		bean.Log.Error(err)
		return err
	}

	return nil
}
